package com.example.shgt.fragment;

import com.google.gson.JsonSyntaxException;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.shgt.DetailsActivity;
import com.example.shgt.LoginActivity;
import com.example.shgt.MyPurchasesActivity;
import com.example.shgt.MyPostsActivity;
import com.example.shgt.R;
import com.example.shgt.TransactionRecordsActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MineFragment extends Fragment {

    private TextView txtUserName;
    private TextView balanceText;
    private ImageView imgHead;

    private final Gson gson = new Gson();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        TextView titleText = view.findViewById(R.id.title_text);
        Button rechargeButton = view.findViewById(R.id.recharge_button);
        Button personalInfoButton = view.findViewById(R.id.personal_info_button);
        Button myPostsButton = view.findViewById(R.id.my_posts_button);
        Button myFavoritesButton = view.findViewById(R.id.my_favorites_button);
        Button logoutButton = view.findViewById(R.id.logout_button);
        txtUserName = view.findViewById(R.id.txtUserName);
        balanceText = view.findViewById(R.id.balance_text);
        imgHead = view.findViewById(R.id.imgHead);

        setUserName();
        setMoney();
        setAvatar();
        String userId = getUserId();
        Log.d("UserId", "用户ID: " + userId);

        rechargeButton.setOnClickListener(v -> {
            showRechargeDialog();
        });

        personalInfoButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), TransactionRecordsActivity.class);
            startActivity(intent);
        });

        myPostsButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MyPostsActivity.class);
            startActivity(intent);
        });

        myFavoritesButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MyPurchasesActivity.class);
            startActivity(intent);
        });

        logoutButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        });

        return view;
    }

    private void showRechargeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("充值");
        builder.setMessage("是否充值100.0元?");

        builder.setPositiveButton("确认", (dialog, which) -> {
            String userId = getUserId();
            if (userId.isEmpty()) {
                Toast.makeText(getActivity(), "用户ID为空，请重新登录", Toast.LENGTH_SHORT).show();
                return;
            }
            String tranMoney = "100";
            Log.d("Recharge", "充值的用户ID: " + userId + ", 充值金额: " + tranMoney);
            post(userId, tranMoney);
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void post(String userId, String tranMoney) {
        new Thread(() -> {
            String url = "https://api-store.openguet.cn/api/member/tran/goods/recharge?tranMoney=" + tranMoney + "&userId=" + userId;

            Headers headers = new Headers.Builder()
                    .add("appId", "479dbe79299a4653ada0432942111871")
                    .add("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                    .add("Content-Type", "application/json")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, ""))
                    .build();

            try {
                OkHttpClient client = new OkHttpClient();
                client.newCall(request).enqueue(callback);
            } catch (Exception ex) {
                ex.printStackTrace();
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getActivity(), "充值请求失败，请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    private void setUserName() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getActivity().MODE_PRIVATE);
        String username = sharedPreferences.getString("username", "默认用户");
        txtUserName.setText("用户名: " + username);
    }

    private void setMoney() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getActivity().MODE_PRIVATE);
        int money = sharedPreferences.getInt("money", 0);
        balanceText.setText("余额: " + money);
    }

    private void setAvatar() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getActivity().MODE_PRIVATE);
        String avatarUrl = sharedPreferences.getString("avatar", "");

        if (!avatarUrl.isEmpty()) {
            Glide.with(this)
                    .load(avatarUrl)
                    .placeholder(R.drawable.placeholder)
                    .into(imgHead);
        }
    }

    private String getUserId() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getActivity().MODE_PRIVATE);
        return sharedPreferences.getString("userId", "");
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            Log.e("NetworkError", "请求失败: " + e.getMessage());

            getActivity().runOnUiThread(() -> {
                Toast.makeText(getActivity(), "充值请求失败，请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
            });
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            try {
                if (!response.isSuccessful()) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getActivity(), "充值失败，错误代码: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                String body = response.body().string();
                Log.d("info", body);

                // 使用非泛型的 ResponseBody 进行解析
                Type jsonType = new TypeToken<MineFragment.ResponseBody>(){}.getType();
                MineFragment.ResponseBody dataResponseBody = gson.fromJson(body, jsonType);
                Log.d("info", dataResponseBody.toString());

                if (dataResponseBody.getCode() == 200) {
                    String data = dataResponseBody.getData();
                    Log.d("Recharge", "充值信息: " + data);

                    // 在主线程显示成功消息并更新余额
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getActivity(), "充值成功: " + data, Toast.LENGTH_SHORT).show();

                        // 更新 SharedPreferences 中的余额
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getActivity().MODE_PRIVATE);
                        int currentBalance = sharedPreferences.getInt("money", 0);
                        int rechargeAmount = 100; // 充值金额，根据需要调整
                        int newBalance = currentBalance + rechargeAmount;
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("money", newBalance);
                        editor.apply();

                        // 刷新余额显示
                        setMoney();
                    });
                } else {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getActivity(), "充值失败，错误信息: " + dataResponseBody.getMsg(), Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (JsonSyntaxException e) {
                Log.e("JSONError", "JSON解析错误: " + e.getMessage());
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getActivity(), "数据解析失败", Toast.LENGTH_SHORT).show();
                });
            } catch (Exception e) {
                Log.e("Error", "处理请求时发生错误: " + e.getMessage());
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getActivity(), "处理请求时发生错误", Toast.LENGTH_SHORT).show();
                });
            }
        }


    };

    public static class ResponseBody {
        private int code;
        private String msg;
        private String data;

        public int getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }

        public String getData() {
            return data;
        }
    }
}
